
local BlockInputField = import("../BlockInputField.lua");
local Connection = import("../Connection.lua");

local Input = commonlib.inherit(BlockInputField);

Input:Property("ClassName", "Input");
Input:Property("InputBlock");               -- 输入块
Input:Property("InputShadowBlock");               -- 输入块

function Input:ctor()
end

function Input:Init(block, opt)
    Input._super.Init(self, block, opt);
    
    self.__input_connection__ = Connection:new():Init(block, nil, opt.check);

    return self;
end

function Input:GetInputBlock()
    return self.__input_connection__:GetConnectionBlock();
end

function Input:IsInput()
    return true;
end

function Input:GetNextBlock()
    return self:GetInputBlock();
end

function Input:GetInputFieldValue() 
    if (not self:GetInputBlock()) then return "" end
    return self:GetInputBlock():GetAllCode();
end

-- 获取xmlNode
function Input:SaveToXmlNode()
    local input_name = self:GetName();
    if (not input_name or input_name == "") then return end 

    local xmlnode = {name = "input", attr = {name = input_name}};
    
    local inputBlock = self:GetInputBlock();
    local subXmlNode = inputBlock and inputBlock:SaveToXmlNode();
    if (subXmlNode) then table.insert(xmlnode, subXmlNode) end

    return xmlnode;
end

function Input:LoadFromXmlNode(xmlnode)
    local inputBlockXmlNode = nil;
    for _, subXmlNode in ipairs(xmlnode) do
        if (subXmlNode.name == "block") then 
            inputBlockXmlNode = subXmlNode;
            break;
        end
    end
    
    if (not inputBlockXmlNode) then return end
    local inputBlock = self:GetBlockly():NewBlockByXmlNode(inputBlockXmlNode);
    if (not inputBlock) then return end
    
    if (self:GetType() == "input_value") then
        self.__input_connection__:Connection(inputBlock.__output_connection__);
    else
        self.__input_connection__:Connection(inputBlock.__previous_connection__);
    end
    
    return self;
end

function Input:ForEach(callback)
    Input._super.ForEach(self, callback);

    local inputBlock = self:GetInputBlock();
    if (inputBlock) then
        inputBlock:ForEach(callback);
    end
end

return Input;